package cn.bugstack.springframework.core.convert.support;

import cn.bugstack.springframework.beans.factory.FactoryBean;
import cn.bugstack.springframework.beans.factory.InitializingBean;
import cn.bugstack.springframework.core.convert.*;
import com.sun.istack.internal.Nullable;

import java.util.Set;

/**
 * 创建类型转换工厂
 */
public class ConversionServiceFactoryBean implements FactoryBean<GenericConversionService>, InitializingBean {
    @Nullable
    private Set<?> converters;

    @Nullable
    private GenericConversionService conversionService;

    @Override
    public GenericConversionService getObject() throws Exception {
        return conversionService;
    }

    @Override
    public Class<?> getObjectType() {
        return conversionService.getClass();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.conversionService = new DefaultConversionService();
        registerConverters(converters, conversionService);
    }

    private void registerConverters(Set<?> converters, ConverterRegistry registry) throws Exception {
        if(converters != null){
            for(Object converter : converters){
                if(converter instanceof GenericConverter){
                    registry.addConverter((GenericConverter) converter);
                }else  if(converter instanceof GenericConverter){
                    registry.addConverter((GenericConverter) converter);
                }else  if(converter instanceof GenericConverter){
                    registry.addConverterFactory((ConverterFactory<?, ?>) converter);
                }else {
                    throw new Exception("Each converter object must implement one of the " +
                            "Converter, ConverterFactory, or GenericConverter interfaces");
                }
            }
        }
    }


    public void setConverters(Set<?> converters) {
        this.converters = converters;
    }
}
